<template>
  <div id="app">
    <h1>{{ msg }}</h1>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="桶名">
        <el-input v-model="bucketName" placeholder="桶名"></el-input>
      </el-form-item>
      <el-form-item label="对象名称">
        <el-input v-model="objectName" placeholder="对象名称"></el-input>
      </el-form-item>
    </el-form>

    <p></p>
    <el-row>
      <el-button type="primary" @click="submit1()">下载对象-通过流下载</el-button>
      <el-button type="primary" @click="submit2()">下载对象-指定范围字节下载流</el-button>
      <el-button type="primary" @click="submit3()">下载对象-获取签名URL下载</el-button>
      <el-button type="primary" @click="submit4()">下载对象-获取永久URL下载</el-button>
    </el-row>

    <p>{{objectStream}}</p>

    <!--通过a标签直接下载文件-->
    <p> {{presignedUrl}}</p>

  </div>
</template>

<script>


  var OSS = require("oss-js-client");

  // Instantiate the OSS client with the endpoint
  var ossClient = new OSS.Client({
    // endPoint: "192.168.1.40",
    endPoint: "127.0.0.1",
    port: 9000,
    useSSL: false,
    accessKey: "username",
    secretKey: "password",
  });

  export default {
    name: "VueOSSObject",
    data() {
      return {
        bucketName: 'mybucket2',
        objectName: 'a.txt',
        objectStream: '',
        presignedUrl: '',
        formInline:{},
        msg: "演示OSSClient-ObjectDownload 对象下载操作",
      };
    },
    methods: {

      //下载文件  解决txt或img 等能够被浏览器直接打开的文件
      downFile(blob) {
        //a标签直接下载文件
        let a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        console.log(a.href);
        a.download = this.objectName;  // 下载文件的名字
        document.body.appendChild(a);
        a.click()
      },

      //下载或预览文件, 根据浏览器支持预览的文件类型
      downOrPreviewFile(url) {
        let a = document.createElement('a');
        a.href = url;  //    后端传来的url
        a.click()
      },

      submit1: function () {
        //将对象下载为流
        var size = 0;
        var data = '';
        ossClient.getObject(this.bucketName, this.objectName, (err, dataStream) => {
            if (err) {
              return console.log(err)
            }
            dataStream.on('data', (chunk) => {
              size += chunk.length;
              data += chunk
            });
            dataStream.on('end', () => {
              console.log('End. Total size = ' + size);
              console.log("End. Total data= " + data);
              this.objectStream = data;

              //二进制转Blob
              let blob = new Blob([data]);
              this.downFile(blob)
            });
            dataStream.on('error', (err) => {
              console.log(err)
            })
          }
        )
      },

      submit2: function () {
        //将对象的指定范围字节下载为流
        var size = 0;
        var data = '';
        // 读取内容,返回0到3范围内字节数据
        // reads 3 bytes from the offset 0.
        //类似 range
        ossClient.getPartialObject(this.bucketName, this.objectName, 0, 3, (err, dataStream) => {
          if (err) {
            return console.log(err)
          }
          dataStream.on('data', (chunk) => {
            size += chunk.length;
            data += chunk
          });
          dataStream.on('end', () => {
            console.log('End. Total size = ' + size);
            console.log("End. Total data= " + data);
            this.objectStream = data;

            //二进制转Blob
            let blob = new Blob([data]);
            this.downFile(blob)
          });
          dataStream.on('error', (err) => {
            console.log(err)
          })
        })
      }
      ,

      submit3: function () {
        //通过生成的签名URL，进行临时的预览或下载, 即使存储桶是私有浏览器/移动客户端也可指向该URL直接预览或下载对象
        // 一天到期. 默认值为7天,最大不超过7天
        //expires in a day.
        ossClient.presignedGetObject(this.bucketName, this.objectName, 24 * 60 * 60, (err, presignedUrl) => {
          if (err) return console.log(err);

          console.log(presignedUrl);
          this.presignedUrl = presignedUrl;

          //下载或预览
          // this.downOrPreviewFile(presignedUrl);

          //下载文件
          fetch(this.presignedUrl).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
            this.downFile(blob)
          })
        });
      },
      //GET 永久URL
      submit4: function () {
        //URL支持 GET DELETE POST PUT 操作公开桶对象
        //浏览器/移动客户端可能会指向此URL，以将对象直接预览/下载/上传/更新等操作（桶策略必须是可读/可写的）
        ossClient.getObjectUrl(this.bucketName, this.objectName, (err, url) => {
          if (err) {
            this.data = err
            return console.log(err);
          } else {
            console.log(url);
            this.data = url
            //下载或预览
            //this.downOrPreviewFile(url);

            //下载文件对象
            fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
              this.downFile(blob)
          })
          }
        });
      },

    },
  }
  ;
</script>

<style scope>
</style>
